package com.xiaoq.matrix.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.matrix.entity.ContentElementEntity;
import com.xiaoq.matrix.repository.IContentElementRepository;
import com.xiaoq.matrix.vo.ContentAndElementVo;
import com.xiaoq.vo.PagingVo;

@Repository
public class ContentElementRepositoryImpl implements IContentElementRepository {
	
	@Autowired
	private Datastore dataStore;
	
	private final static Logger LOG = LoggerFactory.getLogger(ContentElementRepositoryImpl.class);

	@Override
	public List<ContentElementEntity> findContentElementList(ContentAndElementVo contentAndElementVo,
			PagingVo pv) {
		String userId = contentAndElementVo.getUserId();
		String name = contentAndElementVo.getName();
		Long pubStart = contentAndElementVo.getPubStart();
		Long pubEnd = contentAndElementVo.getPubEnd();
		int ps = pv.getPs();
		int pn = (pv.getPn()-1)*ps;
		Query<ContentElementEntity> contentElementQuery = dataStore.createQuery(ContentElementEntity.class);
		contentElementQuery.field("userId").equal(userId);
		List<ContentElementEntity> contentList = null;
		Long total = 0L;
		if (StringUtils.isNotEmpty(name))
			contentElementQuery.field("name").equal(name);
		if (pubStart != null)
			contentElementQuery.filter("createdAt >=", pubStart);

		if (pubEnd != null)
			contentElementQuery.filter("createdAt <=", pubEnd);
		if (contentElementQuery != null) {
			total = (long) contentElementQuery.asList().size();

			if (total != 0) {
				contentElementQuery.offset(pn).limit(ps);
				contentList = contentElementQuery.asList();

			}
		}
		
		pv.setTc(total);
		return contentList;
	}

	@Override
	public boolean addContentElement(ContentElementEntity contentElement) {
		if(contentElement!=null){
			dataStore.save(contentElement);
			return true;
		}
		LOG.info("传递的参数不能为空！");
		return false;
	}

	@Override
	public ContentElementEntity getByUrl(String url) {
		List<ContentElementEntity> elemList = dataStore.createQuery(ContentElementEntity.class).filter("url =", url).asList();
		if (elemList == null || elemList.size() == 0) {
			return null;
		}
		return elemList.get(0);
	}

	@Override
	public ContentElementEntity save(ContentElementEntity entity) {
		dataStore.save(entity);
		return entity;
	}

}
